import axios from 'axios';
import { useAuthStore } from '@/stores/auth';

const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 10000,
});

apiClient.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore();
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理网络错误和浏览器扩展冲突
    if (!error.response) {
      if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
        error.message = '请求超时，请检查网络连接';
      } else if (error.message.includes('Network Error') || 
                 error.message.includes('message port closed')) {
        error.message = '网络连接失败，可能是浏览器扩展冲突或网络问题';
      }
    }
    
    if (error.response?.status === 401) {
      // 清除本地存储的认证信息
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      // 清除apiClient认证头
      delete apiClient.defaults.headers.common['Authorization'];
      // 重定向到登录页
      if (window.location.pathname !== '/login' && window.location.pathname !== '/mobile/login') {
        // 根据设备类型重定向到相应的登录页
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        window.location.href = isMobile ? '/mobile/login' : '/login';
      }
    }
    
    return Promise.reject(error);
  }
);

export { apiClient };
export default apiClient;